
class LocalData {
    constructor(localKey, dataObjKey = 'id') {
        this.localKey = localKey
        this.dataObjKey = dataObjKey
    }
    //捞数据
    getData() {
        let dataStr = localStorage.getItem(this.localKey)
        if (dataStr) {
            return JSON.parse(dataStr)
        } else {
            return []
        }
    }
    //存数据
    saveData(data) {
        let strArr = JSON.stringify(data)
        localStorage.setItem(this.localKey, strArr)
    }
    //为新增数据对象添加个人ID
    addId(newObj) {
        let arr = this.getData()
        newObj[this.dataObjKey] = arr.length > 0 ? arr[arr.length - 1][this.dataObjKey] + 1 : 1
        arr.push(newObj)
        this.saveData(arr)
        return newObj.id
    }
    //删除本地存储中对应id数据对象
    delObj(id) {
        let arr = this.getData()
        if (arr && arr.length > 0) {
            let index = arr.findIndex(ele => {
                return ele[this.dataObjKey] == id
            })
            if (index == -1) return
            arr.splice(index, 1)
        }
        this.saveData(arr)
    }
    ////完成&未完成事件函数
    change(id, done) {
        let arr = this.getData()
        arr.forEach(ele => {
            if (ele.id == id) {
                ele.done = done
            }
        })
        this.saveData(arr)
    }
    //计数器
    counter(){
        let arr = this.getData()
        let todoSum = 0
        let doneSum = 0
        if(arr.length == 0) return
        arr.forEach(ele => {
            if(ele.done){
                doneSum++
            } else {
                todoSum++
            }
        })
        return [todoSum,doneSum]
    }
}
